package br.ufc.customJDBC.routing;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.HashMap;

import net.sf.jsqlparser.JSQLParserException;
import br.ufc.customJDBC.CustomConnection;
import br.ufc.histogram.Histogram;

public class HistogramRouter implements Router {

	private Collection<CustomConnection> connectionPool;
	private HashMap<String, CustomConnection> connections;
	private Histogram histogram;

	public HistogramRouter(Collection<CustomConnection> connectionPool, Histogram histogram){
		this.connectionPool = connectionPool;
		this.connections = new HashMap<String, CustomConnection>();
		this.histogram = histogram;

		for (CustomConnection customConnection : connectionPool) {
			connections.put(customConnection.getIp(), customConnection);
		}
	}

	@Override
	public boolean execute(String sql) throws SQLException {
		boolean ret = true;

		try {
			CustomConnection cc = connections.get(histogram.schedule(sql));
			Statement statement = cc.createStatement();
			ret = statement.execute(sql);
			
			statement.close();

		} catch (JSQLParserException e) {
			e.printStackTrace();
		}

		return ret;
	}

	@Override
	public ResultSet executeQuery(String sql) throws SQLException {
		ResultSet ret = null;

		try {
			CustomConnection cc = connections.get(histogram.schedule(sql));
			Statement statement = cc.createStatement();
			ret = statement.executeQuery(sql);
			
			statement.close();

		} catch (JSQLParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return ret;
	}

	@Override
	public int executeUpdate(String sql) throws SQLException {
		int ret = 0;

		try {
			CustomConnection cc = connections.get(histogram.schedule(sql));
			Statement statement = cc.createStatement();
			ret = statement.executeUpdate(sql);
			
			statement.close();

		} catch (JSQLParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return ret;
	}

}
